import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";


enum KeyType {
  key,
  password,
  fingerprint,
  face,
}
class TabPane extends StatefulWidget {
  final KeyType type;
  final int lockId;
  const TabPane({super.key, required this.type, required this.lockId});

  @override
  State<StatefulWidget> createState() => _TabPaneState();

}

class _TabPaneState extends State<TabPane> {

  final ScrollController _scrollController = ScrollController();
  List _list = [];
  int _total = 0;
  bool _isLoading = false;
  Map _params = {
    "pageNum": 1,
    "pageSize": 10,
  };

  void _getList() async {
    Map resData = {};
    Map<String, dynamic> params = {
      ..._params,
    };
    EasyLoading.show();
    _isLoading = true;
    switch (widget.type) {
      case KeyType.key:
        resData = await lockApi.getKeyList(widget.lockId, params);
        break;
      case KeyType.password:
        resData = await lockApi.getPwdList(widget.lockId, params);
        break;
      case KeyType.fingerprint:
        resData = await lockApi.getFingerprints(widget.lockId, params);
        break;
      case KeyType.face:
        // TODO: Handle this case.
        break;
    }
    EasyLoading.dismiss();
    setState(() {
      _isLoading = false;
      _list.addAll(resData["rows"] ?? []);
      _total = resData["total"] ?? 0;
    });
  }

  void _navigateTo(Map item) {
    switch (widget.type) {
      case KeyType.key:
        Stacker.pushNamed(Keys.DEVICE_LOCK_ELECTRONICKEY_DETAIL, arguments: item);
        break;
      case KeyType.password:
        Stacker.pushNamed(Keys.DEVICE_LOCK_PASSWORDKEY_DETAIL, arguments: item);
        break;
      case KeyType.fingerprint:
        Stacker.pushNamed(Keys.DEVICE_LOCK_FINGERPRINT_DETAIL, arguments: item);
        break;
      case KeyType.face:
      // TODO: Handle this case.
        break;
    }
  }

  Future<void> _refresh() async {
    _list = [];
    _params["pageNum"] = 1;
    _getList();
  }

  void _onScroll() {
    if (_isLoading || _list.length >= _total) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _params["pageNum"] += 1;
        _getList();
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _getList();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _refresh,
      child: _list.isNotEmpty ? ListView.separated(
        controller: _scrollController,
        physics: const AlwaysScrollableScrollPhysics(),
        padding: EdgeInsets.all(ThemeVars.paddingPage),
        itemBuilder: (BuildContext context, index) {
          Map item = _list[index];
          return GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              _navigateTo(item);
            },
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12),
              decoration: const BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(5)),
                color: Colors.white,
              ),
              child: Row(
                children: [
                  DecoratedBox(
                    decoration: BoxDecoration(
                      color: ThemeVars.colorBackground,
                      borderRadius: BorderRadius.all(Radius.circular(50)),
                    ),
                    child: Icon(Icons.person, size: 40, color: ThemeVars.colorTextTer,),
                  ),
                  SizedBox(width: 10,),
                  Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(item["lock"]["lockName"], style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),),
                              // Text("待修改", style: TextStyle(fontSize: 12, color: ThemeVars.colorError),),
                            ],
                          ),
                          SizedBox(height: 4,),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(item["keyName"] ?? item["keyboardPwdName"] ?? item["fingerprintName"], style: TextStyle(fontSize: 12,),),
                              SizedBox(width: 10,),
                              Text("${DateTools.formatTime(item["startDate"], format: "{y}-{m}-{d}")} - ${DateTools.formatTime(item["endDate"], format: "{y}-{m}-{d}")}", style: TextStyle(color: ThemeVars.colorTextTer, fontSize: 12),),
                              SizedBox(width: 10,),
                              Text(item["startDate"] == 0 ? "永久" : "限时", style: TextStyle(color: ThemeVars.colorTextTer, fontSize: 12),),
                            ],
                          )
                        ],
                      )
                  )
                ],
              ),
            ),
          );
        },
        separatorBuilder: (BuildContext context, index) => const SizedBox(height: 12,),
        itemCount: _list.length
      ) : ListView(children: [EmptyData()],),
    );
  }

}